import axios from 'axios'
import Vue from 'vue'
import router from './router/index'

const http = axios.create({
  // baseURL: 'http://localhost:3000/admin/api'
  baseURL: process.env.VUE_APP_API_URL || '/admin/api'
})

// 往请求头加 Authorization
http.interceptors.request.use(config => {
  if (localStorage.token) {
    config.headers.Authorization = 'Bearer ' + (localStorage.token || '')
  }
  return config
}, err => {
  return Promise.reject(err)
})
// 拦截器
http.interceptors.response.use(res => {
  return res
}, err => {
  // console.log(err.response)
  Vue.prototype.$message({
    type: 'error',
    message: err.response.data.message
  })
  // console.log(err.response)
  if (err.response.status === 401) {
    router.push('/login')
  }
  return Promise.reject(err)
})
export default http
